<?php namespace App\Controllers\Admin;

use \App\App;

class Notice extends App
{

    public function __construct(...$params) {
        parent::__construct();
        if (!$this->user) {
            showError("用户尚未登录，请登录后重新打开。", '', '无权限访问');
        } else if ($this->user['group']['id']!=1) {
            showError("用户无权限访问");
        }
    }

    public function index () {
        $page=$this->request->request("page")?$this->request->request("page")-1:0;
        
        $noticeModel=new \App\Models\Notice();
        $this->view->notices=$noticeModel->order("date","DESC")->findAll(5,$page*5);
        
        if ($this->request->isAjax() && $this->request->request("page")) {
            $this->render("admin/notice/ajax","admin/header");
        } else {
            $this->view->total= ceil($noticeModel->countAll()/5);
            $this->view->viewTitle="公告管理";
            $this->render("admin/notice/list","admin/header");
        }
    }

    public function add ($id=null) {        
        if ($id) {
            $noticeModel=new \App\Models\Notice();
            $this->view->notice=$noticeModel->find($id);
        }
        $this->render("admin/notice/add","admin/header");
    }

    public function save() {       
        $content=substr($this->request->post("content"),0,100);
        $notice= [
            'id'=>$this->request->post("id")?:0,
            'content'=>$content,
            'user' => $this->user['id'],
            'date' => time()
        ];
        $noticeModel=new \App\Models\Notice();
        $noticeModel->save($notice);
        if ($noticeModel->error) {
            $this->showJson($noticeModel->error,"Error");
        } else {
            $this->showJson("公告保存成功","Success");
        }
    }

    public function delete($id){
        if (!$id) {
            $this->showJson("没有选择要删除的公告","Error");
        }
        $noticeModel=new \App\Models\Notice();
        $noticeModel->delete($id);
        if ($noticeModel->error) {
            $this->showJson($noticeModel->error,"Error");
        } else {
            $this->showJson("删除公告成功","Success");
        }
    }
}